import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, DrawerProps, Form, FormProps, Input, Radio, Space } from 'antd';

import { store } from '@/store';

import { craeteValidator } from '@/config/rule';
import { RoleStatus, RoleStatusObj, RoleType, RoleTypeObj } from '@/enum/role';
import { roleAdd, roleUpdate } from '@/services/base/jiaoseguanlijiaosexiangguanjiekou';

import { BizObject } from '.';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const submit = useRequest(
    async (values) => {
      const query = {
        ...values
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? roleUpdate(query) : roleAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  const afterOpenChange: DrawerProps['afterOpenChange'] = (open) => {
    if (open) {
      // 编辑回填数据
      if ((args?.type === 'edit' || args?.type === 'detail') && args?.rowData) {
        // 回填数据
        form.setFieldsValue(args.rowData);
      } else {
        form.resetFields();
      }
    }
  };

  return (
    <Drawer
      title={
        {
          add: '新增角色',
          edit: '编辑角色',
          detail: '角色详情'
        }[args?.type as string]
      }
      extra={
        <Space>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={form.submit}
          >
            保存
          </Button>
          <Button onClick={onCancel} disabled={submit.loading}>
            取消
          </Button>
        </Space>
      }
      width="50%"
      open={open}
      afterOpenChange={afterOpenChange}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        initialValues={{
          roleType: RoleType.普通角色,
          state: RoleStatus.启用
        }}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="角色名称"
          name="roleName"
          rules={[
            {
              required: true,
              message: '请输入角色名称'
            }
          ]}
        >
          <Input placeholder="请输入角色名称" readOnly={args?.type === 'detail'} />
        </Form.Item>
        <Form.Item
          label="角色编码"
          name="roleCode"
          rules={[
            {
              required: true,
              message: '请输入角色编码'
            },
            {
              validator: craeteValidator(/^[a-zA-Z0-9]{1,20}$/, '只能输入1-20位字母')
            }
          ]}
        >
          <Input placeholder="请输入角色编码" readOnly={args?.type === 'detail'} />
        </Form.Item>
        <Form.Item
          label="角色类型"
          name="roleType"
          rules={[
            {
              required: true,
              message: '请选择角色类型'
            }
          ]}
        >
          <Radio.Group disabled={args?.type === 'detail'}>
            {Array.from(RoleTypeObj).map(([key, value]) => (
              <Radio value={key} key={key}>
                {value.text}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="状态"
          name="state"
          rules={[
            {
              required: true,
              message: '请选择状态'
            }
          ]}
        >
          <Radio.Group disabled={args?.type === 'detail'}>
            {Array.from(RoleStatusObj).map(([key, value]) => (
              <Radio value={key} key={key}>
                {value.text}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item label="角色说明" name="roleExplain">
          <Input.TextArea
            placeholder="请输入角色说明"
            autoSize={{ minRows: 4, maxRows: 6 }}
            readOnly={args?.type === 'detail'}
          />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
